<script setup>
import { getAlertDetail, getAlerts } from '@/api/alert'
import router from '@/router'
import { useAlertStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'

// 筛选表单数据
const filterForm = reactive({
  alertNo: '',
  alertType: '',
  status: '',
  timeRange: []
})

// 警情类型选项
const alarmTypes = [
  { label: '化工火灾', value: 'CHEMICAL_FIRE' },
  { label: '森林火灾', value: 'FOREST_FIRE' },
  { label: '建筑火灾', value: 'BUILDING_FIRE' },
  { label: '车辆火灾', value: 'VEHICLE_FIRE' }
]

// 状态选项
const statusOptions = [
  { label: '待处理', value: 'PENDING' },
  { label: '处理中', value: 'PROCESSING' },
  { label: '已处理', value: 'PROCESSED' }
]

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

// 表格数据相关
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const tableData = ref([])

// 抽屉相关
const drawerVisible = ref(false)
const currentRow = ref(null)

// 表格行样式
const tableRowClassName = ({ row }) =>
  row.priority === '高' ? 'high-priority-row' : ''

// 获取标签类型
const getAlarmTypeTag = (type) =>
  ({
    化工火灾: 'danger',
    森林火灾: 'warning',
    建筑火灾: 'info',
    车辆火灾: 'success'
  })[type] || ''

const getStatusTag = (status) =>
  ({
    待处理: 'danger',
    处理中: 'warning',
    已处理: 'success'
  })[status] || ''

const getPriorityTag = (priority) =>
  ({
    高: 'danger',
    低: 'warning',
    无: 'info'
  })[priority] || ''

const getPriority = (status) =>
  ({
    待处理: '高',
    处理中: '低',
    已处理: '无'
  })[status] || ''

// 事件处理函数
const handleSearch = () => {
  loading.value = true
  queryAlarmList()
  loading.value = false
}

const resetForm = () => {
  Object.keys(filterForm).forEach((key) => {
    filterForm[key] = Array.isArray(filterForm[key]) ? [] : ''
  })
  queryAlarmList()
}

const handleRowClick = async (row) => {
  const { data } = await getAlertDetail(row.id)
  currentRow.value = { ...data }
  currentRow.value.timeline = generateTimelineByStatus(
    currentRow.value.status,
    currentRow.value.createdTime
  )
  drawerVisible.value = true
}

// 根据不同状态生成时间线
const generateTimelineByStatus = (status, reportTime) => {
  const baseTimeline = [
    {
      content: '接收到报警信息',
      timestamp: reportTime,
      type: 'primary',
      color: '#4834d4'
    }
  ]

  switch (status) {
    case '待处理':
      return baseTimeline

    case '处理中': {
      const processingTime = new Date(
        new Date(reportTime).getTime() + 5 * 60000
      )
      return [
        ...baseTimeline,
        {
          content: '派遣救援机器人',
          timestamp: formatDateTime(processingTime),
          type: 'success',
          color: '#67c23a'
        },
        {
          content: '现场监控回传',
          timestamp: formatDateTime(
            new Date(processingTime.getTime() + 5 * 60000)
          ),
          type: 'info',
          color: '#909399'
        }
      ]
    }

    case '已处理': {
      const processedTime = new Date(new Date(reportTime).getTime() + 5 * 60000)
      return [
        ...baseTimeline,
        {
          content: '派遣救援机器人',
          timestamp: formatDateTime(processedTime),
          type: 'success',
          color: '#67c23a'
        },
        {
          content: '现场监控回传',
          timestamp: formatDateTime(
            new Date(processedTime.getTime() + 5 * 60000)
          ),
          type: 'info',
          color: '#909399'
        },
        {
          content: '任务处理完毕',
          timestamp: formatDateTime(
            new Date(processedTime.getTime() + 60 * 60000)
          ),
          type: 'primary',
          color: '#4834d4'
        }
      ]
    }

    default:
      return baseTimeline
  }
}

// 格式化日期时间
const formatDateTime = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const handleAssign = async (row) => {
  if (row.status != '待处理') {
    ElMessage.error('已处理事件不能进行分配')
    return
  }
  const { data } = await getAlertDetail(row.id)
  const alertStore = useAlertStore()
  alertStore.setAlertInfo(data)
  router.push('/emergency/assign')
}

const queryAlarmList = async () => {
  const { data } = await getAlerts(
    currentPage.value,
    pageSize.value,
    filterForm.alertType,
    filterForm.status,
    filterForm.alertNo,
    filterForm.timeRange[0],
    filterForm.timeRange[1]
  )

  tableData.value = data.list
  total.value = data.total
  loading.value = false
  ElMessage.success('查询成功')
}

onMounted(() => {
  queryAlarmList()
})
</script>

<template>
  <div class="alarm-list-page">
    <!-- 搜索过滤区 -->
    <section class="filter-section">
      <el-card shadow="none">
        <el-form :model="filterForm" inline class="filter-form">
          <el-form-item label="警情编号">
            <el-input
              v-model="filterForm.alertNo"
              placeholder="请输入警情编号"
              clearable
            />
          </el-form-item>
          <el-form-item label="警情类型">
            <el-select
              v-model="filterForm.alertType"
              placeholder="请选择警情类型"
              clearable
            >
              <el-option
                v-for="item in alarmTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态">
            <el-select
              v-model="filterForm.status"
              placeholder="请选择处理状态"
              clearable
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :shortcuts="dateShortcuts"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" class="search-btn">
              <el-icon><i-ep-Search /></el-icon> <span>查询</span>
            </el-button>
            <el-button @click="resetForm" class="reset-btn">
              <el-icon><i-ep-Refresh /></el-icon> <span>重置</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </section>

    <!-- 列表区域 -->
    <section class="list-section">
      <el-card shadow="none">
        <template #header>
          <div class="card-header">
            <span class="title">警情列表</span>
            <div class="actions">
              <el-button
                type="primary"
                @click="queryAlarmList"
                class="refresh-btn"
              >
                <el-icon><i-ep-Refresh /></el-icon>
                <span>刷新</span>
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="tableData"
          class="modern-table"
          stripe
          @row-click="handleRowClick"
          :row-class-name="tableRowClassName"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column type="index" width="50" />
          <el-table-column prop="alertNo" label="警情编号" min-width="200" />
          <el-table-column prop="alertType" label="警情类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getAlarmTypeTag(row.alertType)" round>{{
                row.alertType
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="location"
            label="地点"
            min-width="120"
            show-overflow-tooltip
          />
          <el-table-column prop="createdTime" label="报警时间" width="280" />
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getStatusTag(row.status)" round>{{
                row.status
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="{ row }">
              <el-tag
                :type="getPriorityTag(getPriority(row.status))"
                effect="dark"
                round
                >{{ getPriority(row.status) }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click.stop="handleRowClick(row)">
                <el-icon><i-ep-View /></el-icon> 查看
              </el-button>
              <el-button type="success" link @click.stop="handleAssign(row)">
                <el-icon><i-ep-SetUp /></el-icon> 分配
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
          @size-change="queryAlarmList"
          @current-change="queryAlarmList"
        />
      </el-card>
    </section>

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      size="50%"
      :destroy-on-close="true"
      class="modern-drawer"
    >
      <template #header>
        <div class="drawer-header">
          <h4>警情详情</h4>
          <el-tag :type="getStatusTag(currentRow?.status)" round>{{
            currentRow?.status
          }}</el-tag>
        </div>
      </template>

      <div class="drawer-content" v-if="currentRow">
        <el-descriptions :column="2" border class="modern-descriptions">
          <el-descriptions-item label="警情编号">{{
            currentRow.alertNo
          }}</el-descriptions-item>
          <el-descriptions-item label="警情类型">
            <el-tag :type="getAlarmTypeTag(currentRow.alertType)">{{
              currentRow.alertType
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="报警地点">{{
            currentRow.location
          }}</el-descriptions-item>
          <el-descriptions-item label="报警时间">{{
            currentRow.createdTime
          }}</el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag
              :type="getPriorityTag(getPriority(currentRow.status))"
              effect="dark"
              round
              >{{ getPriority(currentRow.status) }}</el-tag
            >
          </el-descriptions-item>
          <el-descriptions-item
            v-if="currentRow.robots.length"
            label="协作机器人"
            >{{ currentRow.robots.at(0)?.robotName }}</el-descriptions-item
          >
        </el-descriptions>

        <div class="detail-section">
          <h5>现场信息</h5>
          <el-descriptions :column="1" border class="modern-descriptions">
            <el-descriptions-item label="事故描述">{{
              currentRow.incidentDesc
            }}</el-descriptions-item>
            <el-descriptions-item label="环境描述">{{
              currentRow.environmentDesc
            }}</el-descriptions-item>
            <el-descriptions-item label="危险物品">{{
              currentRow.dangerousGoods
            }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h5>处理进度</h5>
          <el-timeline class="modern-timeline">
            <el-timeline-item
              v-for="(activity, index) in currentRow.timeline"
              :key="index"
              :type="activity.type"
              :color="activity.color"
              :timestamp="activity.timestamp"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </div>

        <!-- 检测结果区域 -->
        <div
          class="detail-section"
          v-if="currentRow.detections && currentRow.detections.length"
        >
          <h5>被困人员检测结果</h5>
          <el-table
            :data="currentRow.detections"
            class="modern-table"
            stripe
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            max-height="300"
          >
            <el-table-column
              prop="detectionTime"
              label="检测时间"
              min-width="180"
            />
            <el-table-column prop="count" label="人数" min-width="100" />
            <el-table-column prop="location" label="位置" min-width="150" />
          </el-table>
        </div>
      </div>

      <template #footer>
        <div class="drawer-footer">
          <el-button
            type="primary"
            @click="drawerVisible = false"
            class="edit-btn"
            >关闭</el-button
          >
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
@import '@/assets/scss/abstracts/mixins';
.alarm-list-page {
  padding: 2.4rem;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 搜索过滤区 */
.filter-section {
  margin-bottom: 2.5rem;

  .el-card {
    border-radius: 1.2rem;
    background: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 1rem;
  }

  .filter-form {
    display: flex;
    flex-wrap: wrap;
    gap: 1.6rem;

    .el-form-item {
      margin-bottom: 0;

      :deep(.el-form-item__label) {
        color: #1f2a44;
        font-weight: 350;
        font-size: 1.6rem;
        margin-right: 1.5rem;
      }

      .el-input,
      .el-select,
      .el-date-picker {
        width: 22rem;
        .el-input__wrapper {
          border-radius: 8px;
          box-shadow: none;
        }
      }
    }

    .el-button {
      font-size: 1.6rem;
      @include flexAround;
    }

    .search-btn {
      background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
      border: none;
      border-radius: 8px;
      padding: 1rem 2rem;
      transition: opacity 0.2s;

      &:hover {
        opacity: 0.9;
      }
    }

    .reset-btn {
      border-radius: 8px;
    }
  }
}

/* 列表区域 */
.list-section {
  .el-card {
    border-radius: 1.2rem;
    background: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 0 1rem;
  }

  .card-header {
    @include flexBetween;

    .title {
      font-size: 2rem;
      font-weight: 600;
      color: #1f2a44;
    }

    .actions {
      display: flex;
      gap: 1.2rem;

      .refresh-btn {
        @include flexAround;
        background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
        border: none;
        border-radius: 8px;
        padding: 1rem 2rem;
        font-size: 1.6rem;

        &:hover {
          opacity: 0.9;
        }
      }
    }
  }

  .modern-table {
    border-radius: 8px;
    overflow: hidden;
    font-size: 1.6rem;

    :deep(.el-table__header th) {
      background: #fafafa;
      color: #1f2a44;
      font-weight: 600;
    }

    :deep(.el-table__row) {
      transition: background 0.2s;
      .cell {
        padding: 0.5rem 0;
      }
      .el-button,
      .el-tag {
        font-size: 1.6rem;
      }
      &:hover {
        background: #f9fafc;
      }
    }

    :deep(.high-priority-row) {
      background: #fff5f5;

      &:hover {
        background: #ffebeb;
      }
    }

    .el-tag {
      border-radius: 6px;
      font-weight: 500;
    }
  }

  .pagination {
    margin-top: 2rem;
    display: flex;
    justify-content: flex-end;

    :deep(.el-pager li.is-active) {
      background: #4834d4;
      color: #fff;
    }
  }
}

/* 详情抽屉 */
.modern-drawer {
  :deep(.el-drawer__header) {
    padding: 1.6rem 2.4rem;
    border-bottom: 1px solid #f0f2f5;
    margin-bottom: 0;
  }

  .drawer-header {
    display: flex;
    align-items: center;
    gap: 1.2rem;

    h4 {
      margin: 0;
      font-size: 2rem;
      font-weight: 600;
      color: #1f2a44;
    }

    .el-tag {
      font-weight: 500;
      font-size: 1.6rem;
    }
  }

  .drawer-content {
    padding: 1rem;

    :deep(.el-descriptions__cell) {
      font-size: 1.6rem;

      .el-tag {
        font-size: 1.6rem;
      }
    }
    .detail-section {
      margin-top: 2.4rem;
      margin-bottom: 2.4rem;

      h5 {
        font-size: 1.8rem;
        font-weight: 600;
        color: #1f2a44;
        margin-bottom: 1.2rem;
      }

      .modern-descriptions {
        border-radius: 8px;
        overflow: hidden;

        :deep(.el-descriptions__cell) {
          border-color: #f0f2f5;
          padding: 1.2rem;
        }

        :deep(.el-descriptions__label) {
          background: #fafafa;
          color: #1f2a44;
          font-weight: 500;
        }
      }

      .modern-timeline {
        :deep(.el-timeline-item__node) {
          width: 1.2rem;
          height: 1.2rem;
        }

        :deep(.el-timeline-item__content) {
          color: #1f2a44;
          font-size: 1.6rem;
        }

        :deep(.el-timeline-item__timestamp) {
          color: #86909c;
          font-size: 1.4rem;
        }
      }

      .modern-table {
        border-radius: 8px;
        overflow: hidden;

        :deep(.el-table__header th) {
          background: #fafafa;
          color: #1f2a44;
          font-weight: 600;
          font-size: 1.6rem;
        }

        :deep(.el-table__row) {
          transition: background 0.2s;
          font-size: 1.6rem;
          &:hover {
            background: #f9fafc;
          }
        }
      }
    }
  }

  .drawer-footer {
    padding: 0 2.4rem 2.4rem;
    display: flex;
    justify-content: flex-end;
    gap: 1.2rem;

    .edit-btn {
      background: linear-gradient(135deg, #4834d4 0%, #6b5fe8 100%);
      border: none;
      border-radius: 8px;
      padding: 10px 20px;
      font-size: 1.6rem;

      &:hover {
        opacity: 0.9;
      }
    }
  }
}
</style>
